//
//  GXAudioTool.m
//  音乐播放
//
//  Created by dllo on 16/7/23.
//  Copyright © 2016年 LGX. All rights reserved.
//

#import "GXAudioTool.h"
#import <AVFoundation/AVFoundation.h>
@interface GXAudioTool()<AVAudioPlayerDelegate>


@property (nonatomic, assign) NSInteger number;



@end
@implementation GXAudioTool

+ (instancetype)shareInstance
{
    static GXAudioTool *handler = nil;
    if (handler == nil) {
        handler = [[GXAudioTool alloc]init];
    }
    return handler;
    
}

- (AVAudioPlayer *)playMusicWithNameArrayIndex:(NSInteger )index
{
    [self stop];
    _number = index;
    NSString *string =  _musicArray[index];
    dispatch_queue_t mainQueue = dispatch_get_main_queue();
    dispatch_queue_t globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(globalQueue, ^{
        //在子线程中使用同步方法请求数据
         NSURL *url = [NSURL URLWithString:string];
        //这是一个典型的同步方法
        NSData *data = [NSData dataWithContentsOfURL:url];
        //拿到数据之后给视图赋值
        dispatch_async(mainQueue, ^{
            //更新UI要在主列队进行
            if (_audioPlay == nil) {
    self.audioPlay = [[AVAudioPlayer alloc]initWithData:data error:nil];
    self.audioPlay.delegate = self;
    }
    [_audioPlay play];
            
            
        });
        
        
    });

    
    
    return _audioPlay;
}

/**停止*/
- (void)stop
{
    if (_audioPlay) {
        [_audioPlay stop];
        self.audioPlay.delegate = nil;
        _audioPlay = nil;
    }
}

/**暂停*/
- (void)pause
{
    if (_audioPlay) {
        [_audioPlay pause];
    }
}

/**播放*/
- (void)play
{
    if (_audioPlay) {
        [_audioPlay play];
    }
    
}

-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    
    if (_musicArray.count != 0) {
        if (_number > _musicArray.count - 1) {
        _number = 0;
    }
    [self stop];
    _number++;
        
        if (_number != _musicArray.count) {
            
             [self playMusicWithNameArrayIndex:_number];
        }
   
    NSLog(@"播放结束: %ld", _number);
    
    }
    
}

/**上一首*/
- (void)previousMusic
{
    //获取上一首播放的歌曲
    if (_number != 0) {
        _number -= 1;
        NSLog(@"%ld", _number);
        [self playMusicWithNameArrayIndex:_number];
        
    }
    else
    {
        [self playMusicWithNameArrayIndex: 0];
    }
}
/**下一首*/
- (void)nextMusic
{
    if (_number < _musicArray.count - 1) {
        _number += 1;
        NSLog(@"%ld", _number);
        [self playMusicWithNameArrayIndex:_number];
    }
    else
    {
        [self playMusicWithNameArrayIndex:_musicArray.count - 1];
    }
}



@end
